package com.dingceng.demo.photo

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.dingceng.demo.base.dp
import com.dingceng.demo.base.ui.BaseActivity
import com.dingceng.demo.base.ui.MyGridItemDecoration
import com.dingceng.demo.photo.databinding.PhotoListActivityBinding
import kotlinx.coroutines.*


class PhotoListActivity : BaseActivity<PhotoListActivityBinding>(), View.OnClickListener {
    private val adapter = PhotoAdapter()
    private lateinit var viewModel: PhotoListModel

    override fun provideLayout(): Int {
        return R.layout.photo_list_activity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.click = this
        viewModel = ViewModelProvider(this).get(PhotoListModel::class.java)
        initRecyclerView()
        initObservers()
        test()
    }
    private fun initObservers() {
        viewModel.photoList.observe(this){
            adapter.setList(it)
        }
        viewModel.getData()
    }


    private fun initRecyclerView() {
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        binding.recyclerView.addItemDecoration(MyGridItemDecoration(15.dp, false, 10.dp))
        binding.recyclerView.layoutManager = layoutManager
        binding.recyclerView.adapter = adapter
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.iv_back->{
                finish()
            }
        }
    }

    private fun test() {
        //##1 最推荐使用！需依赖库：'androidx.fragment:fragment-ktx:1.2.0'
        lifecycleScope.launch {
            /**启动协程*/
        }
        //##2
        lifecycleScope.launch(Dispatchers.IO) {
            /**Activity中启动协程,指定协程运行在IO线程*/
            withContext(Dispatchers.Main){
                /**切换到主线程*/
            }
        }
        //##3
        MainScope().launch{
            /**Activity中启动协程*/
        }
        //##4
        val launch = GlobalScope.launch {
            /**此方式启动协程可以任意类中，这种方式启动的协程没有绑定生命周期，需要手动关闭*/
        }
        launch.cancel()/**需要手动关闭*/
    }

}